#include "stdafx.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif
/////////////////////////////////////////////////////////////////////////////////////////////////
void calc_dmi(tagUMyCalcFormula*pFormula,long numCalc,phistory_data paData,double*dataCalc[10],long decNum,long sec_type,_procReflection procReflection)
{
	long i=1;
	double seedPrice(__price_seed__[decNum]);
	double*TR=dataCalc[5],varData1=0,varData2=0;
	double*DMP=dataCalc[4],*DMM=dataCalc[3];
	double*PDI=dataCalc[0],*MDI=dataCalc[1];
	double*ADX=dataCalc[2],*ADXR=dataCalc[3];
	for(;i<numCalc;++i)
	{
		TR[i] = (paData[i].highPx-paData[i].lowPx)/seedPrice;
		varData1 = abs(paData[i].highPx-paData[i-1].ClosePx)/seedPrice;
		varData2 = abs(paData[i-1].ClosePx-paData[i].lowPx)/seedPrice;
		TR[i] = max(max(TR[i],varData1),varData2);

		varData1 = paData[i].highPx-paData[i-1].highPx;
		varData2 = paData[i-1].lowPx-paData[i].lowPx;

		DMP[i] = (varData1>0&&varData1>varData2)?varData1*100:0;
		DMM[i] = (varData2>0&&varData2>varData1)?varData2*100:0;
	}
	UMyCalc_EXPMEMA(TR,numCalc,pFormula->infoParam[0].nowValue);
	UMyCalc_EXPMEMA(DMP,numCalc,pFormula->infoParam[0].nowValue);
	UMyCalc_EXPMEMA(DMM,numCalc,pFormula->infoParam[0].nowValue);

	for(i=1;i<numCalc&&(UMyCalc_invalid(TR[i])
		||UMyCalc_invalid(DMP[i])||UMyCalc_invalid(DMM[i]));++i);
	for(;i<numCalc;++i)
	{
		if(fabs(TR[i])<0.000001)
		{
			if(i)
			{
				PDI[i] = PDI[i-1];
				MDI[i] = MDI[i-1];
			}
		}
		else
		{
			PDI[i] = DMP[i]/TR[i];
			MDI[i] = DMM[i]/TR[i];
		}
	}

	for(i=1;i<numCalc&&(UMyCalc_invalid(PDI[i])||UMyCalc_invalid(MDI[i]));++i);
	for(;i<numCalc;++i)
	{
		varData1 = MDI[i]+PDI[i];
		if(fabs(varData1)<0.000001)
		{
			if(i)
			{
				ADX[i] = ADX[i-1];
			}
		}
		else
		{
			ADX[i] = fabs(MDI[i]-PDI[i])/varData1;
		}
	}
	UMyCalc_EXPMEMA(ADX,numCalc,pFormula->infoParam[1].nowValue);
	memcpy(ADXR,ADX,numCalc*sizeof(double));
	UMyCalc_EXPMEMA(ADXR,numCalc,pFormula->infoParam[1].nowValue);
}

/*
TR:=EXPMEMA(MAX(MAX(HIGH-LOW,ABS(HIGH-REF(CLOSE,1))),ABS(REF(CLOSE,1)-LOW)),N);
HD :=HIGH-REF(HIGH,1);
LD :=REF(LOW,1)-LOW;
DMP:=EXPMEMA(IF(HD>0&&HD>LD,HD,0),N);
DMM:=EXPMEMA(IF(LD>0&&LD>HD,LD,0),N);
PDI: DMP*100/TR;
MDI: DMM*100/TR;
ADX: EXPMEMA(ABS(MDI-PDI)/(MDI+PDI)*100,M);
ADXR:EXPMEMA(ADX,M);
*/
